/*
题目链接:
https://leetcode.cn/problems/maximize-subarrays-after-removing-one-conflicting-pair/?slug=fruits-into-baskets-iii&tab=solutions&tab=3603047&tab=mei-ju-zuo-duan-dian-wei-hu-zui-xiao-ci-4nvu6&region=local_v2
*/

//题解代码:
class Solution {
public:
    #define ll long long
    long long maxSubarrays(int n, vector<vector<int>>& conf) {
        int m = conf.size();
        vector<ll> cnt(n+1);
        ll ans = 0;
        for(int i=0;i<m;++i){
            if(conf[i][0] > conf[i][1]) swap(conf[i][0],conf[i][1]);
        }

        sort(conf.begin(),conf.end(),[&](const vector<int>& p1,const vector<int>& p2)->bool{
            return p1[1] < p2[1];
        });

        for(int i=1,fi=0,sc=0,j=0;i<=n;++i){   
            while(j<m && conf[j][1]<=i){
                if(conf[j][0]>=fi){
                    sc = fi;
                    fi = conf[j][0];
                }else if(conf[j][0]>sc){
                    sc = conf[j][0];
                }
                ++j;
            }
            ans += i - fi;
            cnt[fi] += fi-sc;
        }

        ll mxcnt = 0;
        for(int i=1;i<=n;++i) mxcnt = max(mxcnt,cnt[i]);
        return ans+mxcnt;
        
    }
};
